import { Button, Modal, Space, Statistic, Tooltip } from 'antd';
import React, { useState } from 'react';
import ProCard from '@ant-design/pro-card';
import { ModalForm, ProFormDigit, ProFormText } from '@ant-design/pro-form';
import styles from '../index.less';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { ItemInfoProps } from '@/pages/market/Item';
import { getAuction, getAuctions } from '@/services/aqchain-antd/trade';
import { useModel } from '@@/plugin-model/useModel';
import { formatEther, parseEther } from 'ethers/lib/utils';
import { useRequest } from '@@/plugin-request/request';

const AuctionCard: React.FC = () => {
  // 全局变量
  const { initialState } = useModel('@@initialState');
  if (!initialState) {
    return <div />;
  }
  // 页面变量
  const { item, owner, tokenId, auction, loading, responsive } =
    useModel('item');
  const {
    currentAccount,
    provider,
    contracts: { auctionContract },
  } = initialState;
  if (!item) {
    return <div />;
  }

  // 判断token所有者是否定价交易合约 当所有者为合约地址时 表示token正在进行定价交易
  if (owner !== auctionContract.address || !auction) {
    return <div />;
  }

  // // 非拍卖直接返回空
  // if (item.status !== 3) {
  //   return <></>;
  // }
  //
  // // 获取拍卖记录
  // const { data, loading } = useRequest(() => {
  //   return getAuctions({ fileHash: item.fileHash, createTxHash: item.txHash });
  // });
  //
  // if (loading || !data) {
  //   return <></>;
  // }
  //
  // let createAuction: API.ModelsAuction = {};
  // let bids: API.ModelsAuction[] = [];
  // data.forEach((val) => {
  //   switch (val.type) {
  //     case 'create':
  //       createAuction = val;
  //       break;
  //     case 'bid':
  //       bids.push(val);
  //       break;
  //   }
  // });
  //
  // const { initialState } = useModel('@@initialState');
  // const {
  //   provider,
  //   contracts: { marketContract },
  //   currentAccount,
  // } = initialState!;

  const deadline = auction.end * 1000;

  const bidForm = (
    <ModalForm
      title="设置价格"
      trigger={
        <Button size="large" type="primary">
          出价
        </Button>
      }
      onFinish={async (values) => {
        console.log(values);
        try {
          const signer = await provider.getSigner();
          const gasPrice = await provider.getGasPrice();
          const nonce = await signer.getTransactionCount();
          const overrides = {
            gasPrice: gasPrice.toNumber(),
            gasLimit: 500000,
            nonce: nonce,
            value: parseEther(values.price.toString()),
          };
          await auctionContract.callStatic.bid(tokenId, overrides);
          const tx = await auctionContract
            .connect(signer)
            .bid(tokenId, overrides);
          await tx.wait();
          window.location.reload();
        } catch (e) {
          console.error(e);
        }
        return true;
      }}
    >
      <ProFormDigit
        name="price"
        label="出价"
        rules={[
          {
            type: 'number',
            required: true,
            min: auction.lowestPrice,
          },
        ]}
      />
    </ModalForm>
  );

  const finishForm = (
    <ModalForm<{ highestBid: number; highestBidder: string }>
      title="结束拍卖"
      trigger={<Button size="large">结束拍卖</Button>}
      onFinish={async (values) => {
        try {
          const signer = await provider.getSigner();
          const gasPrice = await provider.getGasPrice();
          const nonce = await signer.getTransactionCount();
          const overrides = {
            gasPrice: gasPrice.toNumber(),
            gasLimit: 500000,
            nonce: nonce,
          };
          await auctionContract.callStatic.finish(tokenId, overrides);
          const tx = await auctionContract
            .connect(signer)
            .finish(tokenId, overrides);
          await tx.wait();
          window.location.reload();
        } catch (e) {
          console.error(e);
        }
        return true;
      }}
    ></ModalForm>
  );

  const sellerActions = currentAccount?.address === auction.seller && (
    <Space>{finishForm}</Space>
  );

  const buyerActions =
    currentAccount?.address !== auction.seller ? [bidForm] : [];

  const columns: ProColumns<API.ModelsAuction>[] = [
    {
      title: '出价人',
      render: (_, record) => {
        return record.seller;
      },
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'money',
    },
  ];

  return (
    <ProCard.Group
      className={styles.itemCard}
      title="进行中的交易"
      headerBordered
      bordered
      direction="row"
      extra={sellerActions}
      actions={buyerActions}
    >
      <ProCard.Group direction={responsive ? 'column' : 'row'}>
        <ProCard>
          <Statistic title="交易类型" value="拍卖出售" />
        </ProCard>
        <ProCard.Divider type={responsive ? 'horizontal' : 'vertical'} />
        <ProCard>
          <Statistic title="起拍价格" value={auction.lowestPrice} />
        </ProCard>
        <ProCard.Divider type={responsive ? 'horizontal' : 'vertical'} />

        <ProCard>
          <Statistic.Countdown title="截止时间" value={deadline} />
        </ProCard>
      </ProCard.Group>
      <ProCard.Divider type="horizontal" />

      <ProCard.Group direction={responsive ? 'column' : 'row'}>
        <ProCard>
          <Statistic title="最高出价" value={formatEther(auction.highestBid)} />
        </ProCard>
        <ProCard.Divider type={responsive ? 'horizontal' : 'vertical'} />
        <ProCard>
          <Statistic title="最高出价人" value={auction.highestBidder} />
        </ProCard>
      </ProCard.Group>
      {/*<ProTable*/}
      {/*  rowKey="txHash"*/}
      {/*  headerTitle="出价列表"*/}
      {/*  options={false}*/}
      {/*  search={false}*/}
      {/*  columns={columns}*/}
      {/*  dataSource={bids}*/}
      {/*  // params={{fileHash:item.fileHash,createTxHash:createAuction?.txHash,type:'bid'}}*/}
      {/*  // request={(params => getAuctions(params))}*/}
      {/*/>*/}
    </ProCard.Group>
  );
};

export default AuctionCard;
